import * as step from '@flow-step/step-toolkit'
import {UploadInputs} from './upload-inputs'
import * as path from 'path'
import * as glob from 'glob';
import * as util from './util'


export async function getInputs(): Promise<UploadInputs> {
    let inputs = {} as unknown as UploadInputs

    if (process.env['WORK_SPACE'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'WORK_SPACE'"
        )
        throw new Error("missing params  'WORK_SPACE'")
    }
    if (process.env['PROJECT_DIR'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'PROJECT_DIR'"
        )
        throw new Error("missing params  'PROJECT_DIR'")
    }
    if (process.env['uploadType'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'uploadType'"
        )
        throw new Error("missing params  'uploadType'")
    }
    if (process.env['ARCHIVE_PATH'] == undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'ARCHIVE_PATH'"
        )
        throw new Error("missing params  'ARCHIVE_PATH'")
    }
    if (process.env['ARTIFACT'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'ARTIFACT'"
        )
        throw new Error("missing params  'ARTIFACT'")
    }
    let artifact = process.env['ARTIFACT']
    if (artifact.indexOf(' ') != -1) {
        step.error(`Artifact name: ${artifact} can not contain spaces`)
        throw new Error('invalid artifact name')
    }
    if (process.env['ARTIFACT_NAME'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'ARTIFACT_NAME'"
        )
        throw new Error("missing params  'ARTIFACT_NAME'")
    }
    if (process.env['DATETIME'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'DATETIME'"
        )
        throw new Error("missing params  'DATETIME'")
    }
    let dateTime = process.env['DATETIME']
    let artifactVersion = process.env['ARTIFACT_VERSION']
    if (artifactVersion === undefined) {
        step.info(
            `Initialize the artifact version is ${process.env['DATETIME']}`
        )
        artifactVersion = dateTime
    } else if (artifactVersion.indexOf(' ') != -1) {
        step.error(
            `Artifact version: ${artifactVersion} can not contain spaces`
        )
        throw new Error('invalid artifact version')
    }
    let repoId = process.env['REPO_ID']
    if (repoId === undefined) {
        step.info("Initialize the default repository is 'flow_generic_repo'")
        repoId = 'flow_generic_repo'
    }
    if (process.env['stepIdentifier'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'stepIdentifier'"
        )
        throw new Error("missing params  'stepIdentifier'")
    }
    if (process.env['FILE_PARENT_ID'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'FILE_PARENT_ID'"
        )
        throw new Error("missing params  'FILE_PARENT_ID'")
    }
    if (process.env['ENGINE_GLOBAL_PARAM_ORGANIZATION_ID'] === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'ENGINE_GLOBAL_PARAM_ORGANIZATION_ID'"
        )
        throw new Error("missing params  'ENGINE_GLOBAL_PARAM_ORGANIZATION_ID'")
    }
    let gitIgnore = process.env['GIT_IGNORE']
    if (gitIgnore === undefined) {
        gitIgnore = 'false'
    }

    inputs.artifact = artifact
    inputs.artifactName = process.env['ARTIFACT_NAME']
    inputs.artifactVersion = artifactVersion
    inputs.bucketName = process.env['BUCKET_NAME']
    inputs.accessKeyId = process.env['ACCESS_KEY_ID']
    inputs.accessKeySecret = process.env['ACCESS_KEY_SECRET']
    inputs.token = process.env['SECURITY_TOKEN']
    inputs.dateTime = dateTime
    inputs.fileId = process.env['FILE_ID']
    inputs.fileParentId = process.env['FILE_PARENT_ID']
    inputs.filePath =  searchFiles(process.env['ARCHIVE_PATH'], process.env['PROJECT_DIR'])
    inputs.gitIgnore = gitIgnore
    inputs.includePathInArtifact = process.env['INCLUDE_PATH_IN_ARTIFACT']
    inputs.orgId = process.env['ENGINE_GLOBAL_PARAM_ORGANIZATION_ID']
    inputs.packageHost = process.env['PACKAGE_HOST']
    inputs.projectDir = process.env['PROJECT_DIR']
    inputs.regionId = process.env['REGION_ID']
    inputs.repoId = repoId
    inputs.stepIdentifier = process.env['stepIdentifier']
    inputs.uploadType = process.env['uploadType']
    inputs.workDir = process.env['WORK_SPACE']
    inputs.credential = process.env['PACKAGES_USER_CREDENTIAL']
    inputs.metaUpload = process.env['metaUpload']
    inputs.authorization = process.env['PACKAGES_AUTHORIZATION']
    inputs.baseUrl = process.env['PACKAGES_BASE_URL']



    return inputs
}

function getMatchedFiles(pattern: string): string[] {
    const files = glob.sync(pattern);
    return files;
}

export function searchFiles(input: string,dir: string): string {
    const parts = input.split(' ').filter(Boolean);
    let finalResults: string[] = [];

    for (const part of parts) {
        let results: string[] = [];

        if (part.startsWith('/')) {
            let dirPattern = path.dirname(part);
            let filePattern = path.basename(part);

            results = getMatchedFiles(path.join(dirPattern, filePattern));
        } else {
            let prefix = dir+ util.SEP
            results=  getMatchedFiles(prefix+part).map(item => item.replace(prefix,'') || '');

        }
        finalResults.push(...results)
    }

    const uniqueResults = Array.from(new Set(finalResults)).sort();

    return uniqueResults.join(' ') || input;
}